<?php
/**
 * Created by xiaosong
 * E-mail:4155433@gmail.com
 * Date: 2019/8/22
 * Time: 9:16
 */

namespace app\api\controller;


use app\common\model\RechargeConfig;
use app\common\model\Users;
use app\common\service\WeChatService;
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;
use Yansongda\Pay\Pay;

class WeChat extends Base
{

    protected static $wechat = [
        'appid' => 'wxfc5a58db32637103', // APP APPID
        'app_id' => 'wxfc5a58db32637103', // APP APPID
        'mch_id' => '1537399441',
        'key' => 'e10a123949ba59abbe56e057f20f883e',
        'notify_url' => 'http://api.haniyuyin.com/we_chat/notify',
//        'cert_client' => './apiclient_cert.pem', // optional，退款等情况时用到
//        'cert_key' => './apiclient_key.pem',// optional，退款等情况时用到
    ];



    /**
     * 公众号充值界面
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * @return \think\response\View
     */
    public function index()
    {
        $data  = WeChatService::getOpenid('snsapi_userinfo');

        $open_id = $data['openid'];

        $phone  = self::getExplain('phone');

        $map['status'] = 1;
        $config = Db::name('recharge_config')->where($map)->select();

        $this->assign([
            'phone'  => $phone,
            'config' => $config,
            'open_id' => $open_id,
        ]);

        return view();
    }

    /**
     * 根据uuid查询用户信息
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function info($id)
    {
        $user = Users::where('uuid',$id)->field('nick_name,uuid,header_img,user_id')->cache(2)->find();
        if (!$user){
            api_return(0,'查询不到用户,请重新输入账号');
        }
        api_return(1,'获取成功',$user);
    }

    public function getSign()
    {
        $data = input('post.');

        $map['status'] = 1;
        $map['r_id']   = $data['id'];
        $config = RechargeConfig::where($map)->find();
        if (!$config){
            api_return(0,'系统繁忙,请稍后重试!');
        }

        try{

            if (is_numeric($data['user_id'])){
                $user_id = $data['user_id'];
            }else{
                $user_id = dehashid($data['user_id']);
            }

            $subject = '哈尼'.$config['money'].'钻充值(id:'.$this->userInfo('uuid',$user_id).')';

            $array['id']   = $data['id'];
            $array['type'] = 'recharge';
            $array['remark'] = $subject;
            $array['user_id'] = $data['user_id'];

            $body = json_encode($array);

            $record['content']     = $body;
            $record['create_time'] = time();
            $record['update_time'] = time();

            $id = Db::name('paysign_record')->insertGetId($record);

            $order = [
                'out_trade_no' => time(),
//                'total_fee' => '1', // **单位：分**
                'total_fee' => $config['price'] * 100, // **单位：分**
                'body' =>  $subject,//自定义参数
                'attach' => $id,
                'openid' => $data['open_id'],
            ];

            $pay = Pay::wechat(self::$wechat)->mp($order);

        }catch (\Exception $e){
            api_return(0,$e->getMessage());
        }

        api_return(1,'获取成功',$pay);
    }

    public function notify()
    {
        $pay = Pay::wechat(self::$wechat);

        try{
            $verify = $pay->verify(); // 是的，验签就这么简单！
            cache('wechatVerify',$verify);
//            $verify =  cache('wechatVerify');

//            dd($verify);

            $map['out_trade_no'] = $verify['transaction_id'];
            $map['trade_no']     = $verify['out_trade_no'];
            $map['pay_type']     = 2;
            $have = Db::name('pay_order')->where($map)->find();
            if ($have){ //订单已处理
                return $pay->success()->send();
            }
//            cache('verify',$verify);
//            $verify = cache('wechat');
            $record = Db::name('paysign_record')->where('id',$verify['attach'])->value('content');
            if (!$record){
                Log::record('查询不到支付签名记录');
            }
            $body = json_decode($record,true);
//            $body = json_decode($verify['attach'],true);
            $total = $verify['cash_fee'] / 100;


            switch ($body['type']){
                case 'recharge'://充值
                    $body['money']  = $total;

                    $this->recharge($body,7);
                    break;

                default:
                    api_return(0,'类型错误');
                    break;
            }
        } catch (Exception $e) {
            // $e->getMessage();
            cache('wechatMsg',$e->getMessage());exit();
        }

        $item['out_trade_no'] = $verify['transaction_id'];
        $item['trade_no']     = $verify['out_trade_no'];
        $item['type']         = $body['type'];
        $item['user_id']      = dehashid($body['user_id']);
        $item['price']        = $total;
        $item['pay_type']     = 2;
        $item['create_time']  = time();
        $item['update_time']  = time();
        Db::name('pay_order')->insert($item);
        return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }


}